<template>
  <view>
    <view class="title">登录</view>
    <view class="title2">请登录~~~~~~</view>
    <view class="username input">
      <input type="text" 
        placeholder="账号"
        v-model="obj.username"
        @blur="validateUsername"
      />
    </view>
    <view class="password input">
      <input type="password" 
        placeholder="密码"
        v-model="obj.password"
        @blur="validatePassword"
      />
      <uni-icons type="eye-slash-filled" size="24" color="rgba(147, 147, 147, 1)"></uni-icons>
    </view>
    <view class="agree">
      <checkbox @click="agreed = !agreed">已阅读并同意</checkbox>
      <view class="clause agree2">用户条款</view>
      <view class="policy agree2">隐私政策</view>
    </view>
    <button @click="login">登录</button>
    <view class="helps">
       <view>帮助</view>|
       <view @click="goToRegister">注册</view>|
       <view>忘记密码</view>|
       <view>快捷登录</view>
     </view>
    <view class="three">
      —————— 第三方账号登录 ——————
    </view>
    <view class="wx">
      <uni-icons type="weixin" size="28" color="rgb(122, 198, 110)"></uni-icons>
      <view>微信账号登录</view>
    </view>
    <ErrorMessage
      v-if="isErrorVisible"
      :message="message"
      :visible="isErrorVisible"
      :type="errorType" 
      @update:visible="isErrorVisible = false" 
    />
  </view>
</template>

<script>
import { api } from '../../utils/api/user.js';
import ErrorMessage from '../../components/errorMessage/errorMessage.vue';

export default {
  components: {
    ErrorMessage,
  },
  data() {
    return {
      obj: {
        username: '',
        password: '',
      },
      agreed: false,
      message: '',
      isErrorVisible: false,
      errorType: 'error', // 默认错误类型
    };
  },
  methods: {
    goToRegister() {
      wx.navigateTo({
        url: '/pages/sign_in/sign_in'
      });
    },
    validateUsername() {
      const usernamePattern = /^[a-zA-Z0-9_-]{3,16}$/; // 验证账号
      if (!this.obj.username) {
        this.message = '账号不能为空';
        this.isErrorVisible = true;
        return false; // 返回 false 表示验证失败
      } else if (!usernamePattern.test(this.obj.username)) {
        this.message = '请输入正确的账号（3-16位的大小写字符或下划线）';
        this.isErrorVisible = true;
        return false; // 返回 false 表示验证失败
      }
      return true; // 返回 true 表示验证通过
    },
    validatePassword() {
      if (!this.obj.password) {
        this.message = '密码不能为空';
        this.isErrorVisible = true;
        return false; // 返回 false 表示验证失败
      }
      return true; // 返回 true 表示验证通过
    },
    saveToken(token) {
      wx.setStorageSync('userToken', token);
    },
    async login() {
      // 验证逻辑
      if (!this.validateUsername()) return;
      if (!this.validatePassword()) return;
      
      if (!this.agreed) {
        this.message = '请阅读并点击同意';
        this.isErrorVisible = true;
        this.errorType = 'warning';
        return;
      }
      
      try {
        // 调用登录API
        const loginResult = await api.login_api(this.obj.username, this.obj.password);
        console.log('登录结果:', loginResult);
        
        // 确保token存在
        if (!loginResult.token) {
          throw new Error('登录成功但未获取到token');
        }
        
        // 准备存储的用户信息
        const userInfoToStore = {
          token: loginResult.token,
          username: this.obj.username
        };
        
        // 添加其他可能存在的用户信息
        if (loginResult.user) {
          Object.assign(userInfoToStore, {
            userId: loginResult.user.id,
            phone: loginResult.user.phone,
            email: loginResult.user.email
          });
        } else if (loginResult.id) {
          userInfoToStore.userId = loginResult.id;
        }
        
        // 保存用户信息
        wx.setStorageSync('userInfo', userInfoToStore);
        console.log('存储的用户信息:', wx.getStorageSync('userInfo'));
        
        // 显示成功提示
        this.message = '登录成功';
        this.isErrorVisible = true;
        this.errorType = 'success';
        
        // 延迟跳转让用户看到成功消息
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
        
      } catch (error) {
        console.error('登录失败:', error);
        
        // 根据错误类型显示不同消息
        if (error.message.includes('token')) {
          this.message = '系统错误：缺少身份令牌';
        } else {
          this.message = error.message || '登录失败，请检查账号密码';
        }
        
        this.isErrorVisible = true;
        this.errorType = 'error';
      }
    },
  },
};
</script>

<style>
  page {
    background-color: #FFF;
  }
  .title {
    margin: 110rpx 0 20rpx 50rpx;
    font-size: 64rpx;
    font-weight: 400;
    letter-spacing: 0rpx;
    line-height: 76rpx;
    color: rgba(51, 62, 99, 1);
    text-align: left;
    vertical-align: top;
  }
  .title2 {
    margin: 0rpx 0 120rpx 50rpx;
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.64rpx;
    line-height: 54rpx;
    color: rgba(147, 147, 147, 1);
    text-align: left;
    vertical-align: top;
  }
  .input {
    display: flex;
    margin: 0rpx 0 44rpx 40rpx;
    padding: 40rpx 0 12rpx 62rpx;
    width: 80%;
    height: 80rpx;
    background: rgba(247, 248, 249, 1);
    border-radius: 20rpx;
  }
  .input input {
    width: 80%;
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.4rpx;
    line-height: 56rpx;
    color: rgba(189, 189, 189, 1);
    text-align: left;
    vertical-align: middle;
  }
  .agree {
    display: flex;
    margin: 20rpx 0 56rpx 66rpx;
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0rpx;
    line-height: 47.36rpx;
    color: rgba(147, 147, 147, 1);
    text-align: left;
    vertical-align: top;
  }
  .agree2 {
    margin-right: 4rpx;
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 1rpx;
    line-height: 44rpx;
    text-decoration-line: underline;
    color: rgba(36, 204, 184, 1);
    text-align: center;
    vertical-align: top;
  }
  
  button {
    margin-bottom: 26rpx;
    width: 619.56rpx;
    height: 108.76rpx;
    background: rgba(36, 204, 184, 1);
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.4rpx;
    line-height: 108.76rpx;
    color: rgba(255, 255, 255, 1);
    text-align: center;
    vertical-align: middle;
  }
  .helps {
    display: flex;
    justify-content: space-between;
    margin: 0 150rpx;
    width: 60%;
    height: 44rpx;
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 1rpx;
    line-height: 44rpx;
    color: rgba(98, 98, 98, 1);
    text-align: center;
    vertical-align: top;
  }
  .three {
    margin: 160rpx 66rpx 12rpx 66rpx;
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0rpx;
    line-height: 40rpx;
    color: rgba(51, 62, 99, 1);
    text-align: center;
    vertical-align: middle;
  }
  .wx {
    padding: 12rpx 170rpx;
    display: flex;
    height: 60rpx;
    margin: 0 66rpx;
    background: rgba(255, 255, 255, 1);
    
    border: 4rpx solid rgba(245, 245, 245, 1);
    
    box-shadow: 0rpx 0rpx 0rpx  rgba(0, 0, 0, 0.25);
    border-radius: 20rpx;
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.4rpx;
    line-height: 56rpx;
    color: rgba(98, 98, 98, 1);
    text-align: center;
    vertical-align: middle;
  }
</style>

